﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Web.Oauth2.impl
{
    public class GithubConnector : OauthConnector
    {
        public GithubConnector(String appkey, String appSecret) : base(appkey, appSecret)
        {
            Type = OauthType.github;
        }

        protected override String CreateAuthorizeUrl(String state)
        {
            StringBuilder sb = new StringBuilder("https://github.com/login/oauth/authorize?");
            sb.Append("scope=user");
            sb.Append("&client_id=" + ClientId);
            sb.Append("&redirect_uri=" + RedirectUri);
            sb.Append("&state=" + state);
            return sb.ToString();
        }

        protected override OauthUser GetOauthUser(String code)
        {
            String accessToken = GetAccessToken(code).access_token;
            String url = "https://api.github.com/user?access_token=" + accessToken;

            String httpString = HttpGet(url);
            if (String.IsNullOrEmpty(httpString))
            {
                return null;
            }
            //var jObject = JsonConvert.DeserializeObject(httpString);
            var jObject = JObject.Parse(httpString);
            OauthUser user = new OauthUser();
            user.Avatar = jObject["avatar_url"].ToString();
            user.OpenId = jObject["id"].ToString();
            user.Nickname = jObject["login"].ToString();
            user.Source = Type.ToString();

            return user;
        }

        public override AccessToken GetAccessToken(String code)
        {

            StringBuilder urlBuilder = new StringBuilder("https://github.com/login/oauth/access_token?");
            urlBuilder.Append("client_id=" + ClientId);
            urlBuilder.Append("&client_secret=" + ClientSecret);
            urlBuilder.Append("&code=" + code);

            String url = urlBuilder.ToString();

            String httpString = HttpGet(url);
            var jObject = JObject.Parse(httpString);
            return new AccessToken(jObject["access_token"].ToString());
        }

        public override AccessToken RefreshAccessToken(string refresh_token)
        {
            throw new NotImplementedException();
        }
    }
}
